package com.example.ncov_management_system.controller;

import com.example.ncov_management_system.dao.ClbumDao;
import com.example.ncov_management_system.dao.StudentDao;
import com.example.ncov_management_system.dao.TeacherDao;
import com.example.ncov_management_system.entity.Login;
import com.example.ncov_management_system.service.LoginService;
import com.example.ncov_management_system.service.StudentService;
import com.example.ncov_management_system.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private ClbumDao clbumDao;


    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/login")
    public String login(Login login, HttpSession session) {
        Login login1 = loginService.login(login, session);
        session.setAttribute("login", login1);
        if (login1.getRole().equals("管理员")) {
            return "redirect:/admin/index";
        } else if (login1.getRole().equals("教师")) {
            return "redirect:/teacher/index";
        } else {
            return "redirect:/student/index";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/toLogin";
    }

    @PostMapping("/edit_password")
    public String editPassword(String password, HttpSession session) {
        Login login = (Login) session.getAttribute("login");
        loginService.editPassword(password, login.getId());
        if (login.getRole().equals("管理员")) {
            return "redirect:/admin/index";
        } else if (login.getRole().equals("教师")) {
            return "redirect:/teacher/index";
        } else {
            return "redirect:/student/index";
        }
    }

    @GetMapping("/admin/index")
    public String adminIndex(Model model) {
        model.addAttribute("studentCount", studentDao.count());
        model.addAttribute("teacherCount", teacherDao.count());
        model.addAttribute("clbumCount", clbumDao.count());
        return "admin_index";
    }
}
